import customerDetailForm from "../../customerDetail.vue";
import { utils, writeFile, readFile } from "xlsx";

import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { hasPerms } from "@/utils/auth";

import {
  customerIndex, customerLogs, getSalesList
} from "@/api/crm";
import { type Ref, reactive, ref, onMounted, h ,createVNode ,toRaw } from "vue";
import { getKeyList,cloneDeep, isAllEmpty,storageLocal, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import {addDrawer, closeAllDrawer} from "@/components/ReDrawer/index";
import forms, {FormProps} from "@/views/system/rate/import.vue";
import {addDialog, closeDialog} from "@/components/ReDialog/index";
import { useRoute } from 'vue-router';
import { SuccessFilled, WarningFilled,Notification } from '@element-plus/icons-vue'
import {message} from "@/utils/message";
import visitForm from "@/views/crm/addVisitForm.vue";
export function useOrders(tableRef: Ref) {
  const route = useRoute();
  const form = reactive({
    name: "",
    search_field: "id",
    search:'',
    search_field2: "", // 添加时间筛选字段
    time: [], // 添加时间范围
    effective_id: null, // 添加跟进人员ID
    status: null,
    gender: "0", // 添加性别字段
    state: "", // 添加国家字段
    diy_status: null, // 添加跟进状态字段
    page: 1,
    limit: 15
  });

  const formRef = ref();
  const shopList = ref([]);
  const sta_order_statc = ref([]);
  const selectValue = ref([]);
  const columnsKey = ref('');
  const dataList = ref([]);
  const loading = ref(true);
  const activeStatus = ref(route.query?.order_status||'-1')
  const selectedNum = ref(0);
  const financial_status_arr = ref([]);
  const salesman_arr = ref([]);
  const shop_group_list_arr = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0, pageSize: 15,pageSizes: [10,20, 40, 60,100,200],
    currentPage: 1, background: true
  });
  function onInputChange(row) {
    row.isModified = true; // 手动标记为已修改
  }
  const dataField = ref(['勾选列','展开','订单编号']);
  const db_fields_all = ref(['勾选列','展开','订单编号']);
  const columns = ref([
    { label: "勾选列", type: "selection", width: 50,disabled:true,fixed:true},
    { label: "客户ID", prop: "id", width: 130, align: "left",disabled:true,fixed:true,sortable: "custom",cellRenderer: ({ row, index }) => (
        <>
          <el-icon onClick={() => addVisitLog(row.id)}><Notification /></el-icon>
          <el-text type="primary" size="small" data-id={row.id} onClick={seeOrderDetail}>{row.id}</el-text>
        </>
      ),},
    { label: "姓名", prop: "fullname", width: 100,sortable: "custom"},
    { label: "邮箱", prop: "email",align:'left', width: 180,sortable: "custom",cellRenderer: ({ row, index }) => (<>{row.email?(row.is_verified==1?<el-icon color="green"><SuccessFilled /></el-icon>:<el-icon><WarningFilled /></el-icon>):''} {row.email}</>)},
    { label: "登录时间", prop: "login_at", width: 130,sortable: "custom"},

    { label: "国家", minWidth: 100, prop: "country.chinese_name"},
    { label: "最后回访时间", minWidth: 100, prop: "last_visit_text"},
    { label: "剩下释放时间", minWidth: 140, prop: "left_time",cellRenderer: ({ row, index }) => (
        row.left_time=='-1'? (<el-text size="small">已释放</el-text>) : (row.left_time>20?
            <el-text type="success" size="small" >{row.left_time}天</el-text>:
            <el-text type="danger" size="small" >{row.left_time}天</el-text>)
      )
    },
    { label: "生日", prop: "birthday", width: 100, align: "left",sortable: "custom"},
    { label: "备注", prop: "note", minWidth: 180},
    { label: "性别", prop: "gender", width: 70},



    { label: "电话", prop: "contact", width: 80},
    { label: "首次付款时间", prop: "first_pay_at", width: 130,sortable: "custom"},
    { label: "最近访问时间", prop: "visit_at", width: 130,sortable: "custom"},
    { label: "最近订单", prop: "last_order_id", minWidth: 120,sortable: "custom"},
    { label: "总订单数", prop: "orders_count", minWidth: 90,sortable: "custom"},
    { label: "总消费金额", prop: "total_spent", minWidth: 110,sortable: "custom"},
    { label: "来源设备", prop: "source_device", minWidth: 110,showOverflowTooltip:true},
    { label: "utm_source", prop: "utm_source", minWidth: 110,sortable: "custom"},
    { label: "utm_medium", prop: "utm_medium", minWidth: 110,sortable: "custom"},
    { label: "标签", prop: "tags", minWidth: 70},//
    { label: "付款时间", prop: "pay_at", minWidth: 120,sortable: "custom"},//
    // { label: "管理员ID", prop: "admin_id", minWidth: 70,sortable: "custom"},//
    { label: "管理员名称", minWidth: 120, prop: "admin_name",showOverflowTooltip:true,},
    { label: "来源域名", minWidth: 120, prop: "domain",showOverflowTooltip:true,sortable: "custom"},
    { label: "IP", minWidth: 110, prop: "ip",showOverflowTooltip:true,sortable: "custom"},
    { label: "加入时间", minWidth: 130, prop: "created_at",sortable: "custom"},
    { label: "最后修改时间", minWidth: 130, prop: "updated_at",sortable: "custom"},
    // { label: "是否订阅", minWidth: 80, prop: "",cellRenderer: ({ row, index }) => row.is_sub==1?'是':'否'},
    // { label: "是否事件订阅", minWidth: 80, prop: "",cellRenderer: ({ row, index }) => row.is_event_sub==1?'是':'否'},
      // { label: "物流支出", minWidth: 80, prop: "current_shipping_price"},
      // { label: "付款时间",  minWidth: 130, prop: "pay_at"},
      // { label: "买家email",  minWidth: 150, prop: "customer_email",showOverflowTooltip:true},
  ]);


  //   `country_id` int(11) DEFAULT NULL COMMENT '所属国家ID',
  //   `default_address` json DEFAULT NULL COMMENT '默认地址',
  //   `addresses` json DEFAULT NULL COMMENT '地址列表',
  //   `sysinfo` json DEFAULT NULL COMMENT '客户系统信息',
  //   `creator_id` int(11) NOT NULL DEFAULT '0' COMMENT '创建用户',
  const searchCondList =  ref([])

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  const getSalemanList = async function (page=1,limit=1000) {
    try {

      const response: any = await getSalesList({page,limit});
      const salesData = response.data || response;

      if (salesData && salesData.data && Array.isArray(salesData.data)) {
        salesman_arr.value = salesData.data;
      } else {
        console.warn('销售人员数据格式不正确:', salesData);
      }
    } catch (error) {
      console.error('获取销售人员列表失败:', error);
    }
  }

  async function onSearch() {
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    loading.value = true;

    // if(form.hasOwnProperty('order_status')&&form.order_status>0)delete form.abnormal_label
    const { data }: any = await customerIndex(form); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    // columns.value = columns.value.filter(x=>data.db_fields.includes(x.label));
    // columnsKey.value = Date.now();
    dataField.value = data.db_fields;
    db_fields_all.value = data.db_fields_all;

    dataList.value = data.data;
    shopList.value = data.shop_list;
    searchCondList.value = data?.search_cond_arr;
    financial_status_arr.value = data?.financial_status_arr;
    shop_group_list_arr.value = data?.shop_group_list;


    selectValue.value = data.selectValue;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;


    setTimeout(() => {
      loading.value = false;
    }, 500);

    expandact();
  }



  function  setBatchSearch(){
    // 兼容 Windows (\r\n) 和 Linux (\n)
    const lineBreak = navigator.platform.includes('Win') ? '\r\n' : '\n';
    // 将指定分隔符（如逗号）转换为换行符，并清理多余空格
    form.search = form.search.replace(/[,;]\s*/g, lineBreak).trim();

    addDialog({
      width: "30%",
      title: "设置批量查询",
      contentRenderer: ({ index }) => (
        <el-form size="small">
          <el-form-item label="查询条件">
            <el-radio-group v-model={form.search_field}>
              {searchCondList.value.map(item => (
                <el-radio value={item.value} disabled={item.value==''}>按{item.name}</el-radio>
              ))}
            </el-radio-group>
          </el-form-item>
          <el-form-item label="查询内容">
            <el-input
              v-model={form.search}
              rows="10"
              type="textarea"
              placeholder="多个回车换行"
            />
          </el-form-item>
        </el-form>
      ),
      closeCallBack: ({ options, args }) => {
        form.search = form.search.split(/\r?\n/).filter(Boolean).join(';');
      }
    });

  }
  function  openDialog(){}


  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  onMounted(async() => {
    // 先获取销售人员列表
    await getSalemanList();

    // 处理URL查询参数
    if (route.query) {
      if (route.query.search_field2) {
        form.search_field2 = route.query.search_field2 as string;
      }
      if (route.query.time) {
        // 处理时间参数，可能是字符串格式 "2024-01-01,2024-01-02"
        const timeStr = route.query.time as string;
        if (timeStr.includes(',')) {
          form.time = timeStr.split(',');
        } else {
          form.time = [timeStr, timeStr];
        }
      }
      if (route.query.effective_id) {
        form.effective_id = Number(route.query.effective_id);
      }
    }

    // 然后执行查询
    onSearch();
  });

  //导出功能
  const export_data = async () => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const { data } = await customerIndex(toRaw({...form,page:1,export:1,limit:10000,'platformOrderId':getKeyList(curSelected, "platformOrderId").join(',')}),'get');
    const res = data.field
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `订单列表${new Date().toISOString()}.xlsx`);
  }

  function seeOrderDetail(e){
    let orderId = e.target.getAttribute('data-id')
    let row1 = ref({})
    row1.value = dataList.value.find(x=>x.id == orderId)
    addDrawer({
      size: '60%',
      title: `订单详情:${orderId}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: true,
      headerStyle:`{ marginBottom: '0px' }`,
      contentRenderer: () =>
        createVNode(customerDetailForm, {
          formInline: row1.value
        }),
    });
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }


  //动态控制展开或折叠
  const expandedRowKeys = ref([])
  function expandact() {
    const type = storageLocal().getItem("expand_orders");
    if(type){
      expandedRowKeys.value = dataList.value.map(row => row.platformOrderId)
    }else{
      expandedRowKeys.value = []
    }
  }
  const expandStatus = storageLocal().getItem("expand_orders")||false

  const sortChange = (k: any) => {
    form.sortField = k.prop
    form.order = k.order=='descending'?'desc':'asc'
    onSearch()
  }
  const stateList = ["US","GB","TJ","TM","KZ","BY","DE","ES","FR","UZ","KG","MD","AC","AD","AF","AG","AI","AL","AM","AO","AQ","AS","AU","AW","AX","BA","BB","BD","BF","BG","BI","BJ","BL","BM","BN","BQ","BS","BT","BV","BW","BZ","CA","CC","CD","CF","CG","CI","CK","CM","CN","CS","CU","CV","CW","CX","CY","DK","DM","DR","EA","EE","EH","EN","ET","FJ","FK","FM","FO","GA","GD","GE","GF","GG","GH","GI","GL","GN","GP","GQ","GS","GU","GW","GY","HK","HR","HT","IC","IE","IL","IM","IN","IO","IS","JE","KE","KH","KI","KN","KY","LA","LC","LI","LK","LR","LS","LU","LV","MC","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MS","MT","MU","MV","MW","MZ","NA","NC","NE","NF","NG","NJ","NO","NR","NU","NZ","PF","PG","PK","PM","PN","PR","PW","QS","RE","RW","SB","SC","SH","SI","SJ","SL","SM","SN","SR","ST","SX","SZ","TC","TF","TG","TK","TL","TO","TP","TS","TV","TZ","UG","UM","VA","VC","VG","VI","VU","WF","WS","XA","XB","XK","XX","YJ","YT","ZA","ZG","ZM","ZN","ZW","ZZ","ES","TR","AZ","MA","LB","DZ","ER","TN","SS","BR","MX","TH","ID","MY","VN","PH","SG","KR","JP","EG","SY","PS","JO","IQ","DJ","KM","SO","TD","OM","QA","KW","AE","BH","SA","YE","LY","SD","MR","LT","JM","CH","IR","AN","FI","PY","AR","GR","UY","CR","DO","PE","IT","TT","SV","CZ","BE","CO","TW","HN","EC","SK","NP","RS","NI","SE","GT","CL","NL","RO","HU","VE","AT","PL","PA","BO","GM","PT"]

  const stateList2 = [
    {"ID":"AE","name":"阿联酋","En":"UNITED EMIRATES"},
    {"ID":"AF","name":"阿富汗","En":"AFGHANISTAN"},
    {"ID":"AL","name":"阿尔巴尼亚","En":"ALBANIA"},
    {"ID":"AM","name":"亚美尼亚","En":"ARMENIA"},
    {"ID":"AO","name":"安哥拉","En":"ANGOLA"},
    {"ID":"AR","name":"阿根廷","En":"ARGENTINA"},
    {"ID":"AT","name":"奥地利","En":"AUSTRIA"},
    {"ID":"AU","name":"澳大利亚","En":"AUSTRALIA"},
    {"ID":"AZ","name":"阿塞拜疆","En":"AZERBAIJAN	REPUBLIC"},
    {"ID":"BD","name":"孟加拉","En":"BANGLADESH"},
    {"ID":"BE","name":"比利时","En":"BELGIUM"},
    {"ID":"BF","name":"布基纳法索","En":"BURKINA FASO"},
    {"ID":"BG","name":"保加利亚","En":"BULGARIA"},
    {"ID":"BH","name":"巴林","En":"BAHREIN"},
    {"ID":"BI","name":"布隆迪","En":"BURUNDI"},
    {"ID":"BJ","name":"贝宁","En":"BENIN"},
    {"ID":"BL","name":"巴勒斯坦","En":""},
    {"ID":"BN","name":"文莱","En":"BRUNEI DARUSSALAM"},
    {"ID":"BO","name":"玻利维亚","En":"BOLIVIA"},
    {"ID":"BR","name":"巴西","En":"BRAZIL"},
    {"ID":"BW","name":"博茨瓦纳","En":"BOTSWANA"},
    {"ID":"BY","name":"白俄罗斯","En":"BYELORUSSIA"},
    {"ID":"CA","name":"加拿大","En":"CANADA"},
    {"ID":"CF","name":"中非","En":"CENTRAL AFRICA"},
    {"ID":"CG","name":"刚果","En":"CONGO"},
    {"ID":"CH","name":"瑞士","En":"SWITZERLAND"},
    {"ID":"CL","name":"智利","En":"CHILE"},
    {"ID":"CM","name":"喀麦隆","En":"CAMEROON"},
    {"ID":"CN","name":"中国","En":"CHINA"},
    {"ID":"CO","name":"哥伦比亚","En":"COLOMBIA"},
    {"ID":"CR","name":"哥斯达黎加","En":"COSTA RICA"},
    {"ID":"CS","name":"捷克","En":"CZECH REPUBIC"},
    {"ID":"CU","name":"古巴","En":"CUBA"},
    {"ID":"CY","name":"塞浦路斯","En":"CYPRUS"},
    {"ID":"CN","name":"中国","En":"CHINA"},
    {"ID":"DE","name":"德国","En":"GERMANY"},
    {"ID":"DK","name":"丹麦","En":"DENMARK"},
    {"ID":"DO","name":"多米尼加共和国","En":"DOMINICAN REPUBLIC"},
    {"ID":"DZ","name":"阿尔及利亚","En":"ALGERIA"},
    {"ID":"EC","name":"厄瓜多尔","En":"ECUADOR"},
    {"ID":"EE","name":"爱沙尼亚","En":"ESTONIA"},
    {"ID":"EG","name":"埃及","En":"EGYPT"},
    {"ID":"ES","name":"西班牙","En":"SPAIN"},
    {"ID":"ET","name":"埃塞俄比亚","En":"ETHIOPIA"},
    {"ID":"FI","name":"芬兰","En":"FINLAND"},
    {"ID":"FJ","name":"斐济","En":"FIJI"},
    {"ID":"FR","name":"法国","En":"FRANCE"},
    {"ID":"GA","name":"加蓬","En":"GABON"},
    {"ID":"GB","name":"英国","En":"UNITED KINGDOM"},
    {"ID":"GD","name":"格林纳达","En":"GRENADA"},
    {"ID":"GE","name":"格鲁吉亚","En":"GEORGIA"},
    {"ID":"GH","name":"加纳","En":"GHANA"},
    {"ID":"GN","name":"几内亚","En":"GUINEA"},
    {"ID":"GR","name":"希腊","En":"GREECE"},
    {"ID":"GT","name":"危地马拉","En":"GUATEMALA"},
    {"ID":"HK","name":"香港特别行政区","En":"HONG KONG"},
    {"ID":"HN","name":"洪都拉斯","En":"HONDURAS"},
    {"ID":"HU","name":"匈牙利","En":"HUNGARY"},
    {"ID":"ID","name":"印度尼西亚","En":"INDONESIA"},
    {"ID":"IE","name":"爱尔兰","En":"IRELAND"},
    {"ID":"IL","name":"以色列","En":"ISRAEL "},
    {"ID":"IN","name":"印度","En":"INDIA"},
    {"ID":"IQ","name":"伊拉克","En":"IRAQ"},
    {"ID":"IR","name":"伊朗","En":"IRAN"},
    {"ID":"IS","name":"冰岛","En":"ICELAND"},
    {"ID":"IT","name":"意大利","En":"ITALY"},
    {"ID":"JM","name":"牙买加","En":"JAMAICA"},
    {"ID":"JO","name":"约旦","En":"JORDAN"},
    {"ID":"JP","name":"日本","En":"JAPAN"},
    {"ID":"KG","name":"吉尔吉斯坦","En":"KYRGYZSTAN"},
    {"ID":"KH","name":"柬埔寨","En":"KAMPUCHEA	CAMBODIA"},
    {"ID":"KP","name":"北朝鲜","En":"KOREA,DEM.PEOPLE’S"},
    {"ID":"KR","name":"韩国","En":"REPUBLIC OF KOREA"},
    {"ID":"KT","name":"科特迪瓦共和国","En":"COTE O’IVOIRE"},
    {"ID":"KW","name":"科威特","En":"KUWATI"},
    {"ID":"KZ","name":"哈萨克","En":"KAZAKHSTAN"},
    {"ID":"LA","name":"老挝","En":"LAOS"},
    {"ID":"LB","name":"黎巴嫩","En":"LEBANON"},
    {"ID":"LC","name":"圣卢西亚","En":"SAINT LUEIA"},
    {"ID":"LI","name":"列支敦士登","En":"LIECHTENSTEIN"},
    {"ID":"LK","name":"斯里兰卡","En":"SRI LANKA"},
    {"ID":"LR","name":"利比里亚","En":"LIBERIA"},
    {"ID":"LT","name":"立陶宛","En":"LITHUANIA"},
    {"ID":"LU","name":"卢森堡","En":"LUXEMBOURG"},
    {"ID":"LV","name":"拉脱维亚","En":"LATVIA"},
    {"ID":"LY","name":"利比亚","En":"LIBYAN"},
    {"ID":"MA","name":"摩洛哥","En":"MOROCCO"},
    {"ID":"MC","name":"摩纳哥","En":"MONACO"},
    {"ID":"MD","name":"摩尔多瓦","En":"MOLDOVA,REPUBLIC OF"},
    {"ID":"MG","name":"马达加斯加","En":"MADAGASCAR"},
    {"ID":"ML","name":"马里","En":"MALI"},
    {"ID":"MM","name":"缅甸","En":"BURMA	MYANMAR"},
    {"ID":"MN","name":"蒙古","En":"MONGOLIA"},
    {"ID":"MO","name":"澳门地区","En":"MACAU"},
    {"ID":"MT","name":"马耳他","En":"MALTA"},
    {"ID":"MU","name":"毛里求斯","En":"MAURITIUS"},
    {"ID":"MW","name":"马拉维","En":"MALAWI"},
    {"ID":"MX","name":"墨西哥","En":"MEXICO"},
    {"ID":"MY","name":"马来西亚","En":"MALAYSIA"},
    {"ID":"MZ","name":"莫桑比克","En":"MOZAMBIQUE"},
    {"ID":"NA","name":"纳米比亚","En":"NAMIBIA"},
    {"ID":"NE","name":"尼日尔","En":"NIGER"},
    {"ID":"NG","name":"尼日利亚","En":"NIGERIA"},
    {"ID":"NI","name":"尼加拉瓜","En":"NICARAGUA"},
    {"ID":"NL","name":"荷兰","En":"NETHERLANDS"},
    {"ID":"NO","name":"挪威","En":"NORWAY"},
    {"ID":"NP","name":"尼泊尔","En":"NEPAL"},
    {"ID":"NZ","name":"新西兰","En":"NEW ZEALAND"},
    {"ID":"OM","name":"阿曼","En":"OMAN"},
    {"ID":"PA","name":"巴拿马","En":"PANAMA"},
    {"ID":"PE","name":"秘鲁","En":"PERU"},
    {"ID":"PG","name":"巴布亚新几内亚","En":"PAPUA NEW GUINEA"},
    {"ID":"PH","name":"菲律宾","En":"PHILIPPINES"},
    {"ID":"PK","name":"巴基斯坦","En":"PAKISTAN"},
    {"ID":"PL","name":"波兰","En":"POLAND"},
    {"ID":"PT","name":"葡萄牙","En":"PORTUGAL"},
    {"ID":"PY","name":"巴拉圭","En":"PARAGUAY"},
    {"ID":"QA","name":"卡塔尔","En":"QATAR"},
    {"ID":"RO","name":"罗马尼亚","En":"ROMANIA"},
    {"ID":"RU","name":"俄罗斯","En":"RUSSIAN FEDERATION"},
    {"ID":"SA","name":"沙特阿拉伯","En":"SAUDI ARABIA"},
    {"ID":"SC","name":"塞舌尔","En":"SEYCHELLES"},
    {"ID":"SD","name":"苏丹","En":"SUDAN"},
    {"ID":"SE","name":"瑞典","En":"SWEDEN"},
    {"ID":"SG","name":"新加坡","En":"SINGAPORE"},
    {"ID":"SI","name":"斯洛文尼亚","En":"SLOVENIA"},
    {"ID":"SK","name":"斯洛伐克","En":"SLOVAKIA"},
    {"ID":"SM","name":"圣马力诺","En":"SAN MARINO"},
    {"ID":"SN","name":"塞内加尔","En":"SENEGAL"},
    {"ID":"SO","name":"索马里","En":"SOMALIA"},
    {"ID":"SY","name":"叙利亚","En":"SYRIA"},
    {"ID":"SZ","name":"斯威士兰","En":"SWAZILAND"},
    {"ID":"TD","name":"乍得","En":"CHAD"},
    {"ID":"TG","name":"多哥","En":"TOGO"},
    {"ID":"TH","name":"泰国","En":"THAILAND"},
    {"ID":"TJ","name":"塔吉克斯坦","En":"TAJIKISTAN"},
    {"ID":"TM","name":"土库曼","En":"TURKMENISTAN"},
    {"ID":"TN","name":"突尼斯","En":"TUNISIA"},
    {"ID":"TR","name":"土耳其","En":"TURKEY"},
    {"ID":"TW","name":"台湾省","En":"TAIWAN"},
    {"ID":"TZ","name":"坦桑尼亚","En":"TANZANIA"},
    {"ID":"UA","name":"乌克兰","En":"UKRAINE"},
    {"ID":"UG","name":"乌干达","En":"UGANDA"},
    {"ID":"US","name":"美国","En":"UNITED STATES"},
    {"ID":"UY","name":"乌拉圭","En":"URUGUAY"},
    {"ID":"UZ","name":"乌兹别克","En":"UZBEKISTAN"},
    {"ID":"VC","name":"圣文森特岛","En":"SAINT VINCENT"},
    {"ID":"VE","name":"委内瑞拉","En":"VENEZUELA"},
    {"ID":"VN","name":"越南","En":"VIET NAM"},
    {"ID":"YE","name":"也门","En":"YEMEN"},
    {"ID":"YU","name":"南斯拉夫联盟","En":"YUGOSLAVIA"},
    {"ID":"ZA","name":"南非","En":"SOUTH AFRICA"},
    {"ID":"ZM","name":"赞比亚","En":"ZAMBIA"},
    {"ID":"ZR","name":"扎伊尔","En":"ZAIRE"},
    {"ID":"ZW","name":"津巴布韦","En":"ZIMBABWE"}
  ]


  function addVisitLog(id){
    function saveVisitLog(options,index){
      const FormRef = formRef.value.getRef();
      const curData = options.props.formInline;
      curData.customer_id = id;
      FormRef.validate(valid => {
        if (valid) {
          customerLogs(curData, "post").then(res => {
            if (res.code === 0) {
              message(`您已成功提交的这条回访数据`, { type: "success" });
              closeDialog(options, index);
              onSearch()
            } else {
              message(`回访失败，原因：${res.message}`, {type: "error"});
            }
          })
        }
      });
    }
    addDialog({
      title: `新增回访记录`,
      props: {
        formInline: JSON.parse(JSON.stringify( {})),//type1编辑，2浏览
      },
      width: "40%",
      draggable: true,
      hideFooter:false,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(visitForm, {ref: formRef, formInline: null}),
      footerButtons: [
        { label: "取消",size: "small",type: "info", btnClick: ({ dialog: { options, index }, button }) => {closeDialog(options, index);}},

        {label: "提交",size: "small",type: "success",
          btnClick: ({ dialog: { options, index }, button }) => {
            saveVisitLog(options,index)
          }
        }
      ],
    });
  }

  return {
    form,expandedRowKeys,loading,columnsKey,sortChange,stateList,stateList2,
    columns,expandStatus,dataList,financial_status_arr,
    shopList,sta_order_statc,selectValue,salesman_arr ,shop_group_list_arr,
    export_data,db_fields_all,
    onSearch,activeStatus,selectedNum,onSelectionCancel,
    resetForm, openDialog, pagination,
    handleSelectionChange,searchCondList,setBatchSearch,
    handleSizeChange, handleCurrentChange
  };
}
